package org.apache.osgimaker.wizard;

import java.util.Iterator;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.core.JavaProject;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;

/**
 * @author Tiger Gui
 * tigergui@gmail.com - Beijing China
 * 
 */
public class AnalyseProjectAction implements IObjectActionDelegate {

	private ISelection selection;
	private final Shell shell = PlatformUI.getWorkbench().getDisplay().getActiveShell();

	@Override
	public void run(IAction action) {
		if (selection instanceof IStructuredSelection) {
			for (Iterator<?> it = ((IStructuredSelection) selection).iterator(); it
					.hasNext();) {
				Object element = it.next();
				IProject project = null;
				if (element instanceof IProject) {
					project = (IProject) element;
				} else if (element instanceof IAdaptable) {
					project = (IProject) ((IAdaptable) element)
							.getAdapter(IProject.class);
				}
				if (project != null) {
					startAnalyseJob(project);
				}
			}
		}
	}

	@Override
	public void selectionChanged(IAction action, ISelection selection) {
		this.selection = selection;
	}

	@Override
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {

	}

	private void startAnalyseJob(IProject project) {		
		final JavaProject jProject = (JavaProject) JavaCore.create(project);
		
		Runnable runnable = new Runnable() {
			public void run() {
				SourceSelectionDialog dialog = new SourceSelectionDialog(shell, jProject);
				dialog.open();
			}
		};
		runnable.run();
	}
}
